package com.sgb.kjwl.view.ui.activity.manage;

import android.content.Context;
import android.content.Intent;
import android.view.KeyEvent;
import android.view.View;
import android.view.inputmethod.EditorInfo;
import android.widget.TextView;

import androidx.databinding.DataBindingUtil;
import androidx.recyclerview.widget.LinearLayoutManager;

import com.androidkun.xtablayout.XTabLayout;
import com.google.android.material.tabs.TabLayout;
import com.sgb.kjwl.AppActivity;
import com.sgb.kjwl.R;
import com.sgb.kjwl.databinding.ActivityEpAssestBinding;
import com.sgb.kjwl.di.manage.DaggerEnterpriseManageComponent;
import com.sgb.kjwl.di.manage.EnterpriseManageModule;
import com.sgb.kjwl.model.entity.enterprise.IpPickSelectEntity;
import com.sgb.kjwl.model.entity.manage.EpAssestEntity;
import com.sgb.kjwl.model.entity.manage.EpAssestTypeEntity;
import com.sgb.kjwl.model.entity.user.AddressEntity;
import com.sgb.kjwl.view.ui.adapter.manage.EpAssetAdapter;
import com.sgb.kjwl.view.widget.IpPopWindow;
import com.sgb.kjwl.view.widget.ThreeLevelAreaWindow;
import com.sgb.kjwl.viewmodel.manage.EpAssestModel;
import com.swgk.core.base.di.AppComponent;
import com.swgk.core.recyclerview.entity.BaseAreaEntity;
import com.swgk.core.util.ClickUtils;
import com.swgk.core.xrecyclerview.XRecyclerView;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.inject.Inject;

/**
 * 企业资产
 */
public class EpAssestActivity extends AppActivity implements TextView.OnEditorActionListener {
    @Inject
    EpAssestModel viewModel;

    private ActivityEpAssestBinding binding;

    EpAssetAdapter assetAdapter;
    List<EpAssestTypeEntity> assetList;//资产类型
    List<IpPickSelectEntity> tradeCategoryDatas;//行业分类

    private List<AddressEntity<List<AddressEntity<List<AddressEntity>>>>> provinceData;//省数据

    private IpPopWindow tradeTypeWindow;
    private ThreeLevelAreaWindow cityPopWindow;//省市弹窗

    Map<String,Object> map;
    //省
    private String provinceNo = "";
    //地区
    private String citiesNo = "";
    private String name1 = "";


    @Override
    protected void setupActivityComponent(AppComponent appComponent) {
        DaggerEnterpriseManageComponent.builder().appComponent(appComponent)
                .enterpriseManageModule(new EnterpriseManageModule(this))
                .build()
                .inject(this);
    }

    public static void start(Context context) {
        Intent intent = new Intent();
        intent.setClass(context, EpAssestActivity.class);
        context.startActivity(intent);
    }


    @Override
    protected void initView() {
        binding = DataBindingUtil.setContentView(this, R.layout.activity_ep_assest);
        binding.include.ivBack.setVisibility(View.VISIBLE);
        binding.include.ivBack.setOnClickListener(view -> finish());
        binding.include.editSearch.setHint("请输入专项资产名称");
        binding.tvPlace.setOnClickListener(this);
        binding.tvMoney.setOnClickListener(this);
        binding.ivShowMore.setOnClickListener(this);
        binding.include.tvSearch.setOnClickListener(this);
        binding.include.editSearch.setOnEditorActionListener(this);
        binding.include.ivCancel.setOnClickListener(this);

        map = new HashMap<>();
        tradeCategoryDatas = new ArrayList<>();
        assetAdapter = new EpAssetAdapter(this, null);
        provinceData = new ArrayList<>();

        LinearLayoutManager layoutManager = new LinearLayoutManager(getActivity());
        binding.recyclerView.setLayoutManager(layoutManager);
        binding.recyclerView.setLoadingMoreEnabled(true);
        binding.recyclerView.setAdapter(assetAdapter);
        binding.recyclerView.setLoadingListener(new XRecyclerView.LoadingListener() {
            @Override
            public void onRefresh() {
                viewModel.getAssestList(false, map);
            }

            @Override
            public void onLoadMore() {
                viewModel.getAssestList(true, map);
            }
        });

        binding.tablayout.setOnTabSelectedListener(new XTabLayout.OnTabSelectedListener() {
            @Override
            public void onTabSelected(XTabLayout.Tab tab) {
                map.put("typeNo", assetList.get(tab.getPosition()).getNo());
                viewModel.getAssestList(false, map);
            }

            @Override
            public void onTabUnselected(XTabLayout.Tab tab) {

            }

            @Override
            public void onTabReselected(XTabLayout.Tab tab) {

            }
        });


        viewModel.getCityData();
        // 省 城市
        cityPopWindow = new ThreeLevelAreaWindow(getActivity()){
            @Override
            protected void provinceClick(BaseAreaEntity baseAreaEntity, int position) {
                super.provinceClick(baseAreaEntity, position);
                if (!provinceNo.equals(baseAreaEntity.getId())) {
                    citiesNo = "";
                }

                provinceNo = baseAreaEntity.getId();
                map.put("provinceNo", provinceNo);
            }

            @Override
            protected void cityClick(BaseAreaEntity baseAreaEntity, int position) {
                super.cityClick(baseAreaEntity, position);
                citiesNo = baseAreaEntity.getId();
                map.put("cityNo", citiesNo);
                name1 = baseAreaEntity.getSimpleName();
            }

            @Override
            protected void reset() {
                super.reset();
                cityPopWindow.dismiss();
                viewModel.getAssestList(false, map);
            }
        };
        cityPopWindow.setBgView(binding.grayLayout);
        cityPopWindow.setThreeListIsGone(false);
        cityPopWindow.setOnResultClick((key1, key2, key3) -> viewModel.getAssestList(false, map));
        cityPopWindow.setOnDisMissClick(() -> {
            if (name1.equals("") || name1.equals("不限")) {
                binding.tvPlace.contentSelect(false, false);
            } else {
                binding.tvPlace.contentSelect(true, false);
            }
        });
    }


    public void contentSelect(boolean isSelect, boolean isUp) {
        if (isSelect) {
            binding.tvMoney.setBackground(getResources().getDrawable(R.drawable.search_new_blue_bg));
            binding.tvAssestMoney.setTextColor(getResources().getColor(R.color.color_main));
            binding.imgTop.setImageDrawable(isUp ? getResources().getDrawable(R.mipmap.icon_up_red) :
                    getResources().getDrawable(R.mipmap.ic_up_arrow_n));
            binding.imgBottom.setImageDrawable(isUp ? getResources().getDrawable(R.mipmap.ic_down_arrow_n) :
                    getResources().getDrawable(R.mipmap.icon_down_red));
        } else {
            binding.tvMoney.setBackground(getResources().getDrawable(R.drawable.search_bg));
            binding.tvAssestMoney.setTextColor(getResources().getColor(R.color.color_tab_one));
            binding.imgTop.setImageDrawable(getResources().getDrawable(R.mipmap.ic_up_arrow_n));
            binding.imgBottom.setImageDrawable(getResources().getDrawable(R.mipmap.ic_down_arrow_n));
        }
    }

    @Override
    protected void init() {
        viewModel.getAssestTypes();
        viewModel.getAssestList(false, map);
    }

    /**
     * 搜索框回调
     */
    @Override
    public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
        closeKeybord();
        if (actionId == EditorInfo.IME_ACTION_SEARCH || (event != null && event.getKeyCode() == KeyEvent.KEYCODE_ENTER)) {
            String searchWord = binding.include.editSearch.getText().toString().trim();
            map.put("assetName", searchWord);
            viewModel.getAssestList(false, map);
        }
        return false;
    }

    int count = 0;

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.tv_place:
                if (!ClickUtils.isDoubleClick()) {
                    binding.tvPlace.contentSelect(false, true);
                    if (provinceData.size() == 0) {
                        viewModel.getCityData();
                    } else {
                        showProvincePopWindow();
                    }
                }
                break;
            case R.id.tv_money:
                if (!ClickUtils.isDoubleClick()) {
                    count += 1;
                    switch (count) {
                        case 1://第一次降序
                            contentSelect(true, false);
                            map.put("moneySort", -1);
                            viewModel.getAssestList(false, map);
                            break;
                        case 2://第二次升序
                            contentSelect(true, true);
                            map.put("moneySort", 1);
                            viewModel.getAssestList(false, map);
                            break;
                        case 3://第三次恢复
                            contentSelect(false, false);
                            map.remove("moneySort");
                            viewModel.getAssestList(false, map);
                            break;
                    }
                    count = count == 3 ? 0 : count;
                }
                break;
            case R.id.iv_show_more:
                if (!ClickUtils.isDoubleClick()) {
                    if (tradeCategoryDatas != null) {
                        showTradeTypePopWindow2(tradeCategoryDatas);
                    }
                }
                break;
            case R.id.tv_search:
                String searchText = binding.include.editSearch.getText().toString().trim();
                map.put("assetName", searchText);
                viewModel.getAssestList(false, map);
                break;
            case R.id.iv_cancel:
                if (!binding.include.editSearch.getText().toString().isEmpty()) {
                    binding.include.editSearch.setText("");
                    map.remove("assetName");
                    viewModel.getAssestList(false, map);
                }
                break;

        }
    }

    public void setTablayout(List<IpPickSelectEntity> datas) {
        tradeCategoryDatas = datas;
        for (int i = 0; i < datas.size(); i++) {
            binding.tablayoutTop.addTab(binding.tablayoutTop.newTab().setText(datas.get(i).getName()));
        }
        binding.tablayoutTop.setOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
            @Override
            public void onTabSelected(TabLayout.Tab tab) {
                map.put("industryTypeNo", tradeCategoryDatas.get(tab.getPosition()).getValue());
                viewModel.getAssestList(false, map);
                tradeTypeWindow.setDefItem(tab.getPosition());
            }

            @Override
            public void onTabUnselected(TabLayout.Tab tab) {

            }

            @Override
            public void onTabReselected(TabLayout.Tab tab) {

            }
        });

        //行业分类
        tradeTypeWindow = new IpPopWindow(getActivity());
        tradeTypeWindow.setBgView(binding.grayLayout);
        tradeTypeWindow.setOnResultClick((type, key2, key3) -> {
            int index = tradeCategoryDatas.indexOf(type);
            binding.tablayoutTop.getTabAt(index).select();
        });
        tradeTypeWindow.setOnDismissListener(() -> binding.ivShowMore.setImageResource(R.mipmap.btn_expand1));
    }


    //行业分类
    public void showTradeTypePopWindow2(List<IpPickSelectEntity> datas) {
        tradeTypeWindow.setData(datas);
        tradeTypeWindow.showPopwindow(binding.tabLayout, 0, 0);
        binding.ivShowMore.setImageResource(R.mipmap.btn_expand_up_gray);
    }

    private void showProvincePopWindow() {
        cityPopWindow.showPopwindow(binding.roomLayout, 0, 0);
    }

    public void showList(List<EpAssestEntity> list, boolean isLoadMore) {
        binding.recyclerView.refreshComplete();
        if (isLoadMore) {
            if (null != list && list.size() > 0) {
                binding.recyclerView.loadMoreComplete();
                assetAdapter.addDatas(list);
            } else {
                binding.recyclerView.setNoMore(true);
            }
            binding.recyclerView.setVisibility(View.VISIBLE);
        } else {
            binding.recyclerView.refreshComplete();
            if (null != list && list.size() > 0) {
                binding.recyclerView.setVisibility(View.VISIBLE);
                binding.emptyView.setVisibility(View.GONE);
                assetAdapter.setDatas(list);
                binding.recyclerView.setLoadingMoreEnabled(true);
            } else {
                assetAdapter.setDatas(null);
                binding.recyclerView.setVisibility(View.GONE);
                binding.emptyView.setVisibility(View.VISIBLE);
            }
        }
    }

    public void showEpAssest(List<EpAssestTypeEntity> list) {
        this.assetList = new ArrayList<>();
        this.assetList = list;
        for (EpAssestTypeEntity entity : list) {
            binding.tablayout.addTab(binding.tablayout.newTab().setText(entity.getName()));
        }
    }

    public void setCityData(List<AddressEntity<List<AddressEntity<List<AddressEntity>>>>> datas, String areaCode) {
        provinceData = datas;
        cityPopWindow.setDataForCompany(datas, true);
    }

}
